<?php

namespace App\Http\Controllers;

use App\Exceptions\InvalidRequestException;
use App\Models\Order;
use Carbon\Carbon;
use Illuminate\Http\Request;

class PaymentController extends Controller
{
    function payByAlipay(Order $order){
        $this->authorize('own', $order);
        if($order->paid_at || $order->closed)
            throw new InvalidRequestException('订单已付款，或已关闭');
        return app('alipay')->web([
            'out_trade_no'=>$order->no,
            'total_amount'=>$order->total_amount,
            'subject'=>'支付 shXlg 的订单 '.$order->no,
        ]);
    }
    function payByWechat(Order $order){
        $this->authorize('own', $order);
        if($order->paid_at || $order->closed)
            throw new InvalidRequestException('订单已付款，或已关闭');
        $code_url= app('wechat_pay')->scan([
            'out_trade_no'=>$order->no,
            'total_fee'=>$order->total_amount*100,
            'body'=>'支付 shXlg 的订单 '.$order->no,
        ])->code_url;
        return new QrCode($code_url);
    }
    function alipayReturn(){
        $data= app('alipay')->verify();
        return $data;
    }
    function alipayNotify(){
        $data= app('alipay')->verify();
        if(in_array($data->trade_status, ['TRADE_SUCCESS', 'TRADE_FINISHED'])){
            $order=Order::where('no', $data->out_trade_no)->first();
            if(!$order->paid_at){
                $order->update([
                    'payment_method'=> 'alipay',
                    'payment_no'=> $data->trade_no,
                    'paid_at'=> Carbon::parse($data->gmt_payment, 'PRC')->timestamp,    //符合要求！
//                'paid_at'=> Carbon::parse($data->gmt_payment, 'PRC'), //得到日期+时间的数据格式，但是时区没有转换成服务器时区
//                'paid_at'=> $data->gmt_payment,   //跟上面一样的错误，时区没转换
//                'paid_at'=> Carbon::now(),        //时区正确，但是时间并非正真的付款时间
                ]);
            }
        }
        return app('alipay')->success();
    }
    function wechatNotify(){
        return 'wechat notify';
    }
}
